﻿/*
 * Netkill
 * 
 * Copyright © 2012 John Granström. All Rights Reserved.
 * 
 * This software is released under the terms and conditions of the BSD license. See 'license.txt' for details.'
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Management;
using System.Net.NetworkInformation;
using System.Threading;

namespace Netkill
{
    public partial class Form1 : Form
    {
        Interfacer inter;
        Processor processor;

        public Button BtnKill
        {
            get
            {
                return this.btnKill;
            }
        }

        public Button BtnRevive
        {
            get
            {
                return this.btnRevive;
            }
        }

        public Form1(Interfacer inter, Processor processor)
        {
            InitializeComponent();

            this.inter = inter;
            this.processor = processor;

            chkStartup.Checked = Global.ShowOnStartup;
            textBox1.Text = Global.SavedMonString;
            RefreshUI();
        }

        /// <summary>
        /// Call to refresh UI with up to date information.
        /// Will internally invoke call on correct thread if needed.
        /// </summary>
        public void RefreshUI()
        {
            if (this.InvokeRequired) // Handle calls from other threads internally
            {
                this.Invoke((Action)delegate() { RefreshUI(); });
                return;
            }

            listView1.Items.Clear();
            bool netup = NetworkInterface.GetIsNetworkAvailable();
            label2.Text = netup ? "Connection up" : "Connection down";

            if (inter.IsKilled)
            {
                btnKill.Enabled = false;
                btnRevive.Enabled = true;
            }
            else
            {
                btnKill.Enabled = true;
                btnRevive.Enabled = false;
            }

            foreach (NetworkInterface ni in inter.LivingInterfaces)
            {
                ListViewItem lvi = new ListViewItem(ni.Name);
                lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi, ni.OperationalStatus.ToString()));
                lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi, ni.NetworkInterfaceType.ToString()));
                listView1.Items.Add(lvi);
            }
        }

        private void btnKill_Click(object sender, EventArgs e)
        {
            btnKill.Enabled = false;

            new Thread(new ThreadStart(delegate()
            {
                inter.DisableLivingInterfaces();
                Thread.Sleep(500);
                RefreshUI();
            })).Start(); ;
        }

        private void btnRevive_Click(object sender, EventArgs e)
        {
            btnRevive.Enabled = false;

            new Thread(new ThreadStart(delegate()
            {
                inter.EnableLivingInterfaces();
                Thread.Sleep(2000); // Let's sleep a while on this thread to let the connection establish itself again
                RefreshUI();
            })).Start(); ;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshUI();
        }

        private void btnDebug_Click(object sender, EventArgs e)
        {
            // Ugly way of displaying some debug stuff
            if (this.Height == 161)
                this.Height = 535;
            else
                this.Height = 161;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text.Equals(Global.SavedMonString))
            {
                btnApply.Enabled = false;
                btnCancel.Enabled = false;
            }
            else
            {
                btnApply.Enabled = true;
                btnCancel.Enabled = true;
            }
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            btnApply.Enabled = false;
            btnCancel.Enabled = false;

            textBox1.Text = TryCorrectInput(textBox1.Text); // Correct common mistakes
            if (processor.RestartMon(textBox1.Text))
            {
                Global.SavedMonString = textBox1.Text;
            }
            else
            {
                MessageBox.Show("Error starting process monitor, possibly badly formatted input string.\nEnter processes to monitor separated with comma.\n\nExample: notepad.exe,calc.exe");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            btnApply.Enabled = false;
            btnCancel.Enabled = false;

            textBox1.Text = Global.SavedMonString;
        }

        /// <summary>
        /// Cope with general input errors for auto correction
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private string TryCorrectInput(string input)
        {
            while (input.StartsWith(","))
                input = input.Remove(0, 1);
            while (input.EndsWith(","))
                input = input.Remove(input.Length - 1);
            return input;
        }

        private void chkStartup_CheckedChanged(object sender, EventArgs e)
        {
            Global.ShowOnStartup = chkStartup.Checked;
        }
    }
}
